% Matlab Code for replication of "Optimal Debt Maturity and Firm Investment"
% by J. Jungherr and I. Schott, September 2020
% This code solves the SHORT-TERM DEBT MODEL
function solve_model(PARMS)

% Initialization
VAL.period  = 1;
VAL.HISTORY = cell(1,1);

% Create empty matrices
setup_matrices

% Solve period T-1
solve_T_1

% Iterate forward solution of T-1 in order to generate approximate values for bond price and value function 
simulate_V

% Solve period T-x
for oo = 1:599
    solve_T_x
end

% Compute stationary distribution
stationary_dist

% Compute model moments
model_moments

%% Collect output for Table 6

% 1) Average firm leverage
Tab6_STD.meanlev        = 100*moment.meanlev;
% 2) Average default rate
Tab6_STD.defrate        = 100*moment.defrate;
% 3) Average STD credit spread
Tab6_STD.meanspread     = 100*moment.meanspread;
% 4) Average LTD share
Tab6_STD.LTDshare       = NaN;

% Real variables
Tab6_STD.AvgK           = moment.AvgK;
Tab6_STD.AggK           = moment.AggK;
Tab6_STD.GDP            = moment.GDP;
Tab6_STD.Cons           = moment.Cons;
    
% Save model output
filename            = sprintf('%s%s','Tab6_STD','.mat');
fullname            = fullfile(PARMS.tabfolder, filename);
save(fullname,'Tab6_STD'); % save as .mat file


%% Compute output for Table 7

% Average firm leverage
Tab7_STD.meanlev        = 100*moment.meanlev;
% Average STD credit spread
Tab7_STD.meanspread     = 100*moment.meanspread;
% Mass of firms
Tab7_STD.mass           = moment.mass;

% Save the output
filename            = sprintf('%s%s','Tab7_STD','.mat');
fullname            = fullfile(PARMS.tabfolder, filename);
save(fullname,'Tab7_STD'); % save as .mat file

